//
//  addPatrolTaskTableVC.m
//  Estate
//
//  Created by wangdongdong on 16/9/5.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "addPatrolTaskTableVC.h"
#import "DefaineCell.h"
#import "SelectConcludeCell.h"
#import "B_wuLiaoCell.h"
#import "QianDTableCell.h"
#import "TableTopStateCell.h"
#import "ScoureCell.h"
#import "H1_ImagesCell.h"
#import "DoubleBtnCell.h"
#import "PictureViewController.h"

#import "InspectProcessRecordModel.h"
#import "UIActionSheet+Common.h"
#import "InspectItemModel.h"



@interface addPatrolTaskTableVC ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

// 附件模型
@property (strong, nonatomic) Tweet *curTweet;
// 图片路径数组
@property (strong, nonatomic) NSMutableArray *selectedAssetURLs;
// 创建时间
@property (copy, nonatomic) NSString *nowTime;
// 检查内容(额外巡检)
@property (copy, nonatomic) NSString *content;
// 检查内容(例行巡检)
@property (copy, nonatomic) NSString *content2;
// 检查情况
@property (copy, nonatomic) NSString *caseStr;
// 备注(检查说明)
@property (copy, nonatomic) NSString *note;
// 分数
@property (copy, nonatomic) NSString *grades;

// 巡检结论
@property (copy, nonatomic) NSString *conclude;

// 检查类数据(一级巡检项)
@property (strong, nonatomic) NSDictionary *inspectItemDic;

// 检查内容数据(二级巡检项)
@property (strong, nonatomic) NSDictionary *inspectItemDic2;

// 已选择的巡检项ID(一级)
@property (copy, nonatomic) NSString *inspectItemID;

// 已选择的巡检项ID(二级)
@property (copy, nonatomic) NSString *inspectItemID2;

//
@property (strong, nonatomic) UIButton *btnView;

// 分值上限
@property (copy, nonatomic) NSString *scoreLimit;

@end

@implementation addPatrolTaskTableVC

// 检查类数据(一级巡检项)
- (NSDictionary *)inspectItemDic {
    if (!_inspectItemDic) {
        _inspectItemDic = [NSDictionary dictionary];
    }
    return _inspectItemDic;
}

// 检查内容数据(二级巡检项)
- (NSDictionary *)inspectItemDic2 {
    if (!_inspectItemDic2) {
        _inspectItemDic2 = [NSDictionary dictionary];
    }
    return _inspectItemDic2;
}

- (NSMutableArray *)selectedAssetURLs {
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"检查任务单";
    //附件模型
    _curTweet = [[Tweet alloc] init];
    self.tableView.bounces = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.scoreLimit = @"5";
    // 获取检查项数据(一级巡检项)
    self.inspectItemDic = [self getInspectItem:@"0"];
    [self loadViews];
    
    //新增 默认额外巡检
    self.ipqc = @"routine";
    self.btnView =[[UIButton alloc]init];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_xjy" object:nil];
    
    //得到项目id
   self.proId= [self getProcessProIdByRecordID:self.IPID];
}

- (void)refresh:(id)sender{
    if(self.selectedAssetURLs != nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }
}

-(void)loadViews {
    //注册单元格
    [self.tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"qCell"];
    [self.tableView registerClass:[SelectConcludeCell class] forCellReuseIdentifier:@"sCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defaine"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"topCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ScoureCell" bundle:nil] forCellReuseIdentifier:@"scoureCell"];
    [self.tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
    
    
    //添加右上方提交按钮
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
}

#pragma  mrak--UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
        return 0.001;
    }else{
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return 4;
        
    }else if (section == 1){
        if ([self.ipqc isEqualToString:@"extra"]) {
            return 6;
        } else {
            return 7;
        }
        
    } else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    long section = indexPath.section;
    long row = indexPath.row;
    
    if (section == 0) {
        return 44;
        
    } else if (section == 1){
        if ([self.ipqc isEqualToString:@"extra"]) {
            if(row == 1 || row == 2 || row == 4) {
                return 100;
                
            } else {
                return 44;
            }
            
        } else {
            if(row == 2 || row == 3 || row == 5) {
                return 100;
                
            } else {
                return 44;
            }
        }
    } else {
        return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件信息"];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    long section = indexPath.section;
    long row = indexPath.row;
    
    if (section == 0) {
        if (row == 0) {
            TableTopStateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"topCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.title.text = [NSString stringWithFormat: @"%@%@检查任务单", [LSUtility dateNow], DEF_PERSISTENT_GET_OBJECT(@"realname")];
            return cell;
            
        } else if (row == 1) {  // 项目名
            DefaineCell *dCell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            dCell.selectionStyle=UITableViewCellSelectionStyleNone;
            dCell.title.text = @"项   目:";
            if(self.IPID){
                NSString *proName=[LSUtility getProjectNameByProjectId:self.proId][@"PROJECT_NAME"];
                dCell.text.text=DEFISNUL(proName);
            }
            
            return  dCell;
            
        } else if (row == 2) {  // 记录人
            DefaineCell *dCell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            dCell.selectionStyle=UITableViewCellSelectionStyleNone;
            dCell.title.text = @"记录人:";
            dCell.text.text = DEF_PERSISTENT_GET_OBJECT(@"realname");
            return dCell;
            
        } else {    // 时间
            DefaineCell *dCell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            dCell.selectionStyle=UITableViewCellSelectionStyleNone;
            dCell.title.text=@"时   间:";
            self.nowTime = [LSUtility nowTime];
            dCell.text.text = self.nowTime;
            return dCell;
        }
        
    } else if (section == 1) {
        
        if ([self.ipqc isEqualToString:@"extra"]) {     // 额外巡检
            if (row == 0) {
                DoubleBtnCell *cell=[DoubleBtnCell cellWithTableView:tableView];
                cell.edit = YES;
                cell.extraClickBtn = ^() {
                    
                    weakSelf.inspectItemID = nil;
                    [weakSelf.btnView removeFromSuperview];
                    weakSelf.content2 = nil;
                    weakSelf.ipqc = @"extra";
                    weakSelf.scoreLimit = @"5";
                    self.grades = nil;
                    [weakSelf.tableView reloadData];
                };
                
                cell.rountine = ^(){
                    weakSelf.inspectItemID = nil;
                    weakSelf.inspectItemID2 = nil;
                    weakSelf.content = nil;
                    weakSelf.ipqc = @"routine";
                    self.grades = nil;
                    [weakSelf.tableView reloadData];
                };
                return cell;
                
            } else if (row == 1) {  // 额外巡检(检查内容)
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"检查内容";
                cell.text.placeholder = @"请填写检查内容";
                cell.text.text = self.content ? self.content : @"";
                cell.textValueChangedBlock = ^(NSString *cStr) {
                    self.content = cStr;
                };
                return cell;
                
            } else if (row == 2) {  // 检查情况
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"检查情况:";
                cell.text.placeholder = @"请输入检查情况";
                cell.text.text = self.caseStr ? self.caseStr : @"";
                cell.textValueChangedBlock = ^(NSString *cStr) {
                    self.caseStr = cStr;
                };
                return cell;
                
            } else if (row == 3) {  // 结论(是否合格)
                SelectConcludeCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sCell" forIndexPath:indexPath];
                cell.isEdit = YES;
                cell.lastBtn.selected = NO;
                cell.title.text = @"结   论:";
                self.conclude = self.conclude ? self.conclude : @"0";
                
                cell.clickQualifiedBlock = ^ {
                    self.conclude = @"1";
                };
                cell.clickUnqualifiedBlock = ^ {
                    self.conclude = @"0";
                };
                cell.clickNoRelateBlock = ^ {
                    self.conclude = @"2";
                };
                
                // 设置选中项
                [cell setBtntype:self.conclude];
                return cell;
                
            } else if (row == 4) {  // 备注(检查说明)
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"备   注:";
                cell.text.placeholder = @"请输入备注";
                cell.text.text = self.note ? self.note : @"";
                
                cell.textValueChangedBlock = ^(NSString *cStr) {
                    self.note = cStr;
                };
                return cell;
                
            } else {    // 分数
                ScoureCell *cell = [tableView dequeueReusableCellWithIdentifier:@"scoureCell" forIndexPath:indexPath];
                cell.scoreLimit = self.scoreLimit;
                cell.view = self.navigationController.view;
                cell.title.text = @"评   分:";
                cell.title.font = [UIFont systemFontOfSize:17];
//                cell.textFile.text = self.grades ? self.grades : self.scoreLimit;
                
                cell.textFile.text = self.scoreLimit;

                cell.textBlock = ^(NSString *value) {
                    self.grades = value;
                    NSLog(@"分数:%@",self.grades);
                };
                return cell;
            }
        } else {    // 例行巡检
            if (row == 0) {
                DoubleBtnCell *cell=[DoubleBtnCell cellWithTableView:tableView];
                cell.edit=YES;
                cell.routineBtn.selected = YES;
                cell.extraClickBtn = ^() {
                    weakSelf.inspectItemID = nil;
                    weakSelf.inspectItemID2 = nil;
                    [weakSelf.btnView removeFromSuperview];
                    weakSelf.content2 = nil;
                    weakSelf.ipqc = @"extra";
                    weakSelf.scoreLimit = @"5";
                    self.grades = nil;
                    [weakSelf.tableView reloadData];
                };
                
                cell.rountine = ^() {
                    weakSelf.inspectItemID = nil;
                    weakSelf.inspectItemID2 = nil;
                    weakSelf.content = nil;
                    weakSelf.ipqc = @"routine";
                    self.grades = nil;
                    [weakSelf.tableView reloadData];
                };
                return cell;
                
            } else if (row == 1) {
                DefaineCell *dCell = [tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                dCell.selectionStyle = UITableViewCellSelectionStyleNone;
                dCell.title.text = @"检  查  类:";
                dCell.text.text = @"请选择检查类";
                return dCell;
                
            } else if (row == 2) {  // 二级检查项
                B_wuLiaoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.title.text = @"检查内容:";
                cell.text.placeholder = @"请选择检查内容";
                cell.text.text = self.content2 ? self.content2 : @"";
                //能编辑或者新增
                [self.btnView  addTarget:self action:@selector(clickItem) forControlEvents:UIControlEventTouchUpInside];
                self.btnView .frame = cell.contentView.bounds;
                [cell.contentView addSubview:self.btnView ];
                return cell;
                
            } else if (row == 3) {  // 检查情况
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"检查情况:";
                cell.text.placeholder = @"请输入检查情况";
                cell.text.text = self.caseStr ? self.caseStr : @"";
                
                cell.textValueChangedBlock = ^(NSString *cStr) {
                    self.caseStr = cStr;
                };
                return cell;
                
            } else if (row == 4) {  // 结论(是否合格)
                SelectConcludeCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sCell" forIndexPath:indexPath];
                cell.isEdit = YES;
                cell.lastBtn.selected = NO;
                cell.title.text = @"结   论:";
                self.conclude = self.conclude ? self.conclude : @"0";
                
                cell.clickQualifiedBlock = ^ {
                    self.conclude = @"1";
                };
                cell.clickUnqualifiedBlock = ^ {
                    self.conclude = @"0";
                };
                cell.clickNoRelateBlock = ^ {
                    self.conclude = @"2";
                };
                
                // 设置选中项
                [cell setBtntype:self.conclude];
                return cell;
                
            } else if (row == 5) {  // 备注(检查说明)
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"备   注:";
                cell.text.placeholder = @"请输入备注";
                cell.text.text = self.note ? self.note : @"";
                cell.textValueChangedBlock = ^(NSString *cStr) {
                    self.note = cStr;
                };
                return cell;
                
            } else {    // 分数
                ScoureCell *cell = [tableView dequeueReusableCellWithIdentifier:@"scoureCell" forIndexPath:indexPath];
                cell.scoreLimit = self.scoreLimit;
                cell.view = self.navigationController.view;
                cell.title.text = @"评   分:";
                cell.title.font = [UIFont systemFontOfSize:17];
//                cell.textFile.text = self.grades ? self.grades : self.scoreLimit;
                
                cell.textFile.text = self.scoreLimit;

                cell.textBlock = ^(NSString *value){
                    self.grades = value;
                    NSLog(@"分数:%@",self.grades);
                };
                return cell;
            }
        }
    } else {    // 图片附件
        WEAKSELF
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        cell.isEdit = YES;
        [cell setTitle:@"附件信息"];
        [cell setTitleColor:[UIColor colorWithRed:0.22 green:0.64 blue:0.59 alpha:1.00]];
        cell.curTweet = _curTweet;
        
        cell.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        
        cell.deleteTweetImageBlockUrl = ^(TweetImage *toDelete,NSString *deUrl){
            //移除图片
            [weakSelf.curTweet deleteATweetImage:toDelete];
            //移除数组
            [weakSelf.selectedAssetURLs removeObject:deUrl];
            
            [weakSelf refresh:nil];
        };
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        return cell;
    }
}

/*
 *点击方法
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    long section=indexPath.section;
    long row=indexPath.row;
    NSNumber *ninit = [NSNumber numberWithInteger:0];
    
    if ([self.ipqc isEqualToString:@"routine"]  && section == 1 && row == 1) {     // 一级巡检项(检查项)
        // 检查类数据源(名字)
        NSArray *nameArr = self.inspectItemDic[@"NAME_ARR"];
        if (nameArr.count > 0) {
            [ActionSheetStringPicker showPickerWithTitle:nil rows:@[nameArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                //得到选择下标
                int iv = [(NSNumber *)[selectedIndex firstObject] intValue];
                DefaineCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                cell.text.text = nameArr[iv];
                
                // 获取二级检查项数据(巡检项)
                self.inspectItemID = self.inspectItemDic[@"ID_ARR"][iv];
                
                // 获取分值上限
                self.scoreLimit = [LSUtility getInspectScore:self.inspectItemID];
                // 刷新分值
                NSIndexPath *indexPath3 = [NSIndexPath indexPathForRow:6 inSection:1];
                // 刷新二级巡检项(检查内容)
                self.content2 = nil;
                NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:2 inSection:1];
                [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath2, indexPath3, nil] withRowAnimation:UITableViewRowAnimationNone];
                
            } cancelBlock:nil origin:self.view];
            
        } else {
            [LSUtility showToastWithMessage:@"无可添加的例行巡检类" inView:self.navigationController.view Andtime:1.];
        }
    }
}

- (void)clickItem {
    WEAKSELF
    if (!self.inspectItemID) {
        [LSUtility showToastWithMessage:@"请选择检查类" inView:self.navigationController.view Andtime:1.];
        
    } else {
        // 获取二级检查项数据(巡检项)
        self.inspectItemDic2 = [self getInspectItem2:self.inspectItemID];
        // 检查内容数据源(名字)
        NSArray *nameArr = self.inspectItemDic2[@"NAME_ARR"];
        
        if (nameArr.count > 0) {
            NSNumber *ninit = [NSNumber numberWithInteger:0];
            [ActionSheetStringPicker showPickerWithTitle:nil rows:@[nameArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                
                //得到选择下标
                int iv = [(NSNumber *)[selectedIndex firstObject] intValue];
                self.content2 = nameArr[iv];
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:1];
                [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
                
                self.inspectItemID2 = self.inspectItemDic2[@"ID_ARR"][iv];
                // 获取分值上限
                self.scoreLimit = [LSUtility getInspectScore:self.inspectItemID2];
                
                // 刷新分值
                NSIndexPath *indexPath3 = [NSIndexPath indexPathForRow:6 inSection:1];
                [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath3, nil] withRowAnimation:UITableViewRowAnimationNone];
                
            } cancelBlock:nil origin:self.view];
            
        } else{
            [LSUtility showToastWithMessage:@"无可添加的例行巡检项" inView:self.navigationController.view Andtime:1.];
        }
    }
}

// 获取检查类数据
- (NSDictionary *)getInspectItem:(NSString *)parentID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_ITEM WHERE PARENT_ID = '%@'", parentID];
    FMResultSet *result = [db executeQuery:sql];
    
    // 模型数组
    NSMutableArray *modelArr = [NSMutableArray array];
    NSDictionary *dic;
    // 检查项名字数组
    NSMutableArray *nameArr = [NSMutableArray array];
    // ID数组
    NSMutableArray *IDArr = [NSMutableArray array];
    while ([result next]) {
        InspectItemModel *model = [[InspectItemModel alloc] init];
        
        model.ID = [result stringForColumn:@"ID"];
        model.PARENT_ID = [result stringForColumn:@"PARENT_ID"];
        model.INSPECT_NAME = [result stringForColumn:@"INSPECT_NAME"];
        model.INSPECT_SHORT_NAME = [result stringForColumn:@"INSPECT_SHORT_NAME"];
        model.INSPECT_NUMBER = [result stringForColumn:@"INSPECT_NUMBER"];
        model.INSPECT_SERIOURS_LEVEL = [result stringForColumn:@"INSPECT_SERIOURS_LEVEL"];
        model.INSPECT_SCORE = [result stringForColumn:@"INSPECT_SCORE"];
        model.INSPECT_TITLE = [result stringForColumn:@"INSPECT_TITLE"];
        model.INSPECT_DESC = [result stringForColumn:@"INSPECT_DESC"];
        model.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        model.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        model.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        model.CREATE_IP = [result stringForColumn:@"CREATE_IP"];
        model.MODIFY_USER_NAME = [result stringForColumn:@"MODIFY_USER_NAME"];
        model.MODIFY_IP = [result stringForColumn:@"MODIFY_IP"];
        model.MODIFY_TIME = [result stringForColumn:@"MODIFY_TIME"];
        
        [modelArr addObject:model];
        [nameArr addObject:model.INSPECT_NAME];
        [IDArr addObject:model.ID];
    }
    [db close];
    dic = @{@"NAME_ARR":nameArr, @"ID_ARR":IDArr};
    return dic;
}

// 获取当前检查类的巡检项数据
- (NSDictionary *)getInspectItem2:(NSString *)parentID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_ITEM WHERE PARENT_ID = '%@' AND ID NOT IN (SELECT INSPECT_ITEM_ID FROM INSPECT_USER_ITEM WHERE INSPECT_USER_ID = '%@' AND INSPECT_PROCESS_ID = '%@')", parentID, USERID, self.IPID];
    FMResultSet *result = [db executeQuery:sql];
    
    // 模型数组
    NSMutableArray *modelArr = [NSMutableArray array];
    NSDictionary *dic;
    // 检查项名字数组
    NSMutableArray *nameArr = [NSMutableArray array];
    // ID数组
    NSMutableArray *IDArr = [NSMutableArray array];
    while ([result next]) {
        InspectItemModel *model = [[InspectItemModel alloc] init];
        
        model.ID = [result stringForColumn:@"ID"];
        model.PARENT_ID = [result stringForColumn:@"PARENT_ID"];
        model.INSPECT_NAME = [result stringForColumn:@"INSPECT_NAME"];
        model.INSPECT_SHORT_NAME = [result stringForColumn:@"INSPECT_SHORT_NAME"];
        model.INSPECT_NUMBER = [result stringForColumn:@"INSPECT_NUMBER"];
        model.INSPECT_SERIOURS_LEVEL = [result stringForColumn:@"INSPECT_SERIOURS_LEVEL"];
        model.INSPECT_SCORE = [result stringForColumn:@"INSPECT_SCORE"];
        model.INSPECT_TITLE = [result stringForColumn:@"INSPECT_TITLE"];
        model.INSPECT_DESC = [result stringForColumn:@"INSPECT_DESC"];
        model.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        model.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        model.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        model.CREATE_IP = [result stringForColumn:@"CREATE_IP"];
        model.MODIFY_USER_NAME = [result stringForColumn:@"MODIFY_USER_NAME"];
        model.MODIFY_IP = [result stringForColumn:@"MODIFY_IP"];
        model.MODIFY_TIME = [result stringForColumn:@"MODIFY_TIME"];
        
        [modelArr addObject:model];
        [nameArr addObject:model.INSPECT_NAME];
        [IDArr addObject:model.ID];
    }
    [db close];
    dic = @{@"NAME_ARR":nameArr, @"ID_ARR":IDArr};
    return dic;
}


-(NSString *)getProcessProIdByRecordID:(NSString *)recordId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select pro_id from inspect_process where ID=(select INSPECT_PROCESS_ID from inspect_process_record where inspect_process_id='%@')",recordId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *ids;
    while ([resule next]) {
        ids=[resule stringForColumn:@"pro_id"];
    }
    [db close];
    return ids;
}
#pragma mark--保存
- (void)clickSave {
    
    // 是否有此单独的一级巡检项
    BOOL exist = [self checkWhetherExist:self.inspectItemID];
    
    if ([self.ipqc isEqualToString:@"extra"] && !self.content) {
        [LSUtility showToastWithMessage:@"请填写检查内容" inView:self.navigationController.view Andtime:1.];
        
    } else if ([self.ipqc isEqualToString:@"routine"] && !self.inspectItemID && !self.inspectItemID2) {
        [LSUtility showToastWithMessage:@"请选择检查类" inView:self.navigationController.view Andtime:1.];
        
    } else if ([self.ipqc isEqualToString:@"routine"] && self.inspectItemID && !self.inspectItemID2 && exist) {
        [LSUtility showToastWithMessage:@"已有该巡检项,请重新选择" inView:self.navigationController.view Andtime:1.];
        
    } else if (!self.caseStr) {
        [LSUtility showToastWithMessage:@"请填写检查情况" inView:self.navigationController.view Andtime:1.];
    } else {
        
        // 用户巡检项表
        [self addSInspectUserItemData];
        
        // 刷新列表页
        [[NSNotificationCenter defaultCenter] postNotificationName:@"editInspect" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

// 判断是否已存在一级巡检项
- (BOOL)checkWhetherExist:(NSString *)inspectItemID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_USER_ITEM WHERE INSPECT_ITEM_ID = '%@' AND INSPECT_PROCESS_ID = '%@' AND INSPECT_USER_ID = '%@'", inspectItemID, self.IPID, USERID];
    FMResultSet *result = [db executeQuery:sql];
    
    if ([result next]) {
        [db close];
        return YES;
    } else {
        [db close];
        return NO;
    }
}

# pragma mark - 新增用户巡检项表
- (void)addSInspectUserItemData {
    NSString *ID = [NSUUID UUID].UUIDString;
    
    // 状态为1的巡检记录
    [self addFlowRecordData:ID];
    // 状态为2或是5的巡检记录
    [self addFlowRecordData2:ID];
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    DBHelper *dbhelper = [DBHelper help];
    
    // 巡检组ID
    NSString *sql = [NSString stringWithFormat:@"SELECT INSPECT_GROUP_ID FROM INSPECT_PROCESS WHERE ID = '%@'", self.IPID];
    FMResultSet *IGReult = [db executeQuery:sql];
    
    NSString *IGID;
    while ([IGReult next]) {
        IGID = [IGReult stringForColumn:@"INSPECT_GROUP_ID"];
    }
    
    // 巡检项ID
    NSString *IIID;
    if (self.content) {
        IIID = @"";
    } else {
        if (self.inspectItemID && self.inspectItemID2) {
            IIID = self.inspectItemID2;
        } else if (self.inspectItemID && !self.inspectItemID2) {
            IIID = self.inspectItemID;
        }
    }
    
    // 巡检状态
    NSString *state;
    if ([self.conclude intValue] == 2) {
        state = @"5";
    } else {
        state = @"2";
    }
    
    //字段及对应值
    NSDictionary *pragameDic = [NSDictionary dictionary];
    pragameDic = @{
                   @"ID":DEFISNUL(ID),
                   @"INSPECT_ADDTIONAL_NAME":DEFISNUL(self.content),
                   @"INSPECT_PROCESS_ID":DEFISNUL(self.IPID),
                   @"INSPECT_GROUP_ID":DEFISNUL(IGID),
                   @"INSPECT_USER_ID":DEFISNUL(USERID),
                   @"INSPECT_USER_TYPE":@"2",
                   @"INSPECT_USER_DESC":@"",
                   @"INSPECT_ITEM_ID":DEFISNUL(IIID),
                   @"INSPECT_DESC":DEFISNUL(self.note),
                   @"INSPECT_CURRENT_STATE":state,
                   @"SUPER_PROCESS_ID":@"",
                   @"EXTEND_INFO":@"",
                   @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   @"CREATE_TIME":DEFISNUL(self.nowTime),
                   @"CREATE_IP":[LSUtility getIPAddress],
                   @"MODIFY_USER_NAME":@"",
                   @"MODIFY_TIME":DEFISNUL(self.nowTime),
                   @"MODIFY_IP":[LSUtility getIPAddress],
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"ADD",
                   };
    BOOL isAdd = [dbhelper DataBase:db insertKeyValues:pragameDic intoTable:INSPECT_USER_ITEM];
    if (isAdd) {
        NSLog(@"用户巡检项添加成功");
    } else {
        NSLog(@"用户巡检项添加失败");
    }
    [db close];
}

# pragma mark - 新增巡检流程记录
- (void)addFlowRecordData:(NSString *)inspectUserItemID {
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    // 巡检项ID
    NSString *IIID;
    if (self.content) {
        IIID = @"";
    } else {
        if (self.inspectItemID && self.inspectItemID2) {
            IIID = self.inspectItemID2;
        } else if (self.inspectItemID && !self.inspectItemID2) {
            IIID = self.inspectItemID;
        }
    }
    
    //字段及对应值
    NSDictionary *pragameDic = [NSDictionary dictionary];
    pragameDic = @{
                   @"ID":[NSUUID UUID].UUIDString,
                   @"INSPECT_USER_ITEM_ID":DEFISNUL(inspectUserItemID),
                   @"PRO_ID":DEFISNUL(self.proId),
                   @"INSPECT_PROCESS_ID":DEFISNUL(self.IPID),
                   @"INSPECT_USER_ID":DEFISNUL(USERID),
                   @"INSPECT_ITEM_ID":DEFISNUL(IIID),
                   @"INSPECT_ITEM_STATE":@"1",
                   @"INSPECT_INFO":@"",
                   @"INSPECT_DESC":@"",
                   @"INSPECT_RESULT":@"",
                   @"INSPECT_SCORE":@"",
                   @"INSPECT_ITEM_RECIFICATE_LEADER":@"",
                   @"INSPECT_RECIFICATE_DESC":@"",
                   @"INSPECT_RECIFICATE_REVIEW_USER":@"",
                   @"INSPECT_RECIFICATE_REVIRE_SCORE":@"",
                   @"INSPECT_RECIFICATE_REVIEW":@"",
                   @"INSPECT_DO_TIME":DEFISNUL(self.nowTime),
                   @"EXTEND_INFO":@"",
                   @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   @"CREATE_TIME":DEFISNUL(self.nowTime),
                   @"CREATE_IP":[LSUtility getIPAddress],
                   @"MODIFY_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   @"MODIFY_IP":[LSUtility getIPAddress],
                   @"MODIFY_TIME":DEFISNUL(self.nowTime),
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"ADD",
                   };
    BOOL isAdd = [dbhelper DataBase:db insertKeyValues:pragameDic intoTable:INSPECT_PROCESS_RECORD];
    if (isAdd) {
        NSLog(@"巡检记录添加成功");
    } else {
        NSLog(@"巡检记录添加失败");
    }
}

# pragma mark - 新增巡检流程记录
- (void)addFlowRecordData2:(NSString *)inspectUserItemID {
    NSString *ID = [NSUUID UUID].UUIDString;
    [self insertAttachment:ID];
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    // 巡检项ID
    NSString *IIID;
    if (self.content) {
        IIID = @"";
    } else {
        if (self.inspectItemID && self.inspectItemID2) {
            IIID = self.inspectItemID2;
        } else if (self.inspectItemID && !self.inspectItemID2) {
            IIID = self.inspectItemID;
        }
    }
    
    // 分数
    if (!self.grades) {
        self.grades = self.scoreLimit;
    }
    
    // 巡检状态
    NSString *state;
    if ([self.conclude intValue] == 2) {
        state = @"5";
        
    } else {
        state = @"2";
    }
    
    //字段及对应值
    NSDictionary *pragameDic = [NSDictionary dictionary];
    pragameDic = @{
                   @"ID":DEFISNUL(ID),
                   @"INSPECT_USER_ITEM_ID":DEFISNUL(inspectUserItemID),
                   @"PRO_ID":DEFISNUL(self.proId),
                   @"INSPECT_PROCESS_ID":DEFISNUL(self.IPID),
                   @"INSPECT_USER_ID":DEFISNUL(USERID),
                   @"INSPECT_ITEM_ID":DEFISNUL(IIID),
                   @"INSPECT_ITEM_STATE":state,
                   @"INSPECT_INFO":DEFISNUL(self.caseStr),
                   @"INSPECT_DESC":DEFISNUL(self.note),
                   @"INSPECT_RESULT":self.conclude,
                   @"INSPECT_SCORE":DEFISNUL(self.grades),
                   @"INSPECT_ITEM_RECIFICATE_LEADER":@"",
                   @"INSPECT_RECIFICATE_DESC":@"",
                   @"INSPECT_RECIFICATE_REVIEW_USER":@"",
                   @"INSPECT_RECIFICATE_REVIRE_SCORE":@"",
                   @"INSPECT_RECIFICATE_REVIEW":@"",
                   @"INSPECT_DO_TIME":[LSUtility nowTime],
                   @"EXTEND_INFO":@"",
                   @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   @"CREATE_TIME":[LSUtility nowTime],
                   @"CREATE_IP":[LSUtility getIPAddress],
                   @"MODIFY_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   @"MODIFY_IP":[LSUtility getIPAddress],
                   @"MODIFY_TIME":[LSUtility nowTime],
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"ADD",
                   };
    BOOL isAdd = [dbhelper DataBase:db insertKeyValues:pragameDic intoTable:INSPECT_PROCESS_RECORD];
    if (isAdd) {
        NSLog(@"巡检记录添加成功");
    } else {
        NSLog(@"巡检记录添加失败");
    }
}

#pragma mark - 先新增附件表
- (NSArray *)insertAttachment:(NSString *)recordIds {
    NSArray *rFileArr;
    if (self.selectedAssetURLs.count > 0) {
        rFileArr = [LSUtility insertAttachmentFromArray:self.selectedAssetURLs andRecordId:recordIds andType:@"INSPECT_01" andRecifyState:@"0"];
    }
    return rFileArr;
}

// 将字典或者数组转化为JSON串
- (NSString *)toJSONData:(id)theData{
    NSString *jsonString = nil;
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:0
                                                         error:&error];
    
    if ([jsonData length] != 0 && error == nil){
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else{
        NSLog(@"转JSON失败%@", error);
    }
    return jsonString;
}



/*
 *  此方法让cell横线置顶
 */
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

#pragma mark UIActionSheet M

- (void)showActionForPhoto{
    [self.view endEditing:YES];
    //  @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (self.curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages=[[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock = ^(NSMutableArray *array) {
//            for (NSString *path in array) {
//                //添加图片路径到已选数组
//                [self.selectedAssetURLs addObject:path];
//            }
            self.selectedAssetURLs = array;
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RefreshImage_xjy" object:nil];
}



@end
